<html>
<head>
<title>test</title>
    <style type="text/css">
    body, div, table { font-size: 10pt }
    button, input, select { font-size: 8pt }
    </style>

    <script type="text/javascript" src="http://xml.truveo.com/TruveoVideoSearchAPIv3.js"></script>
    <script type="text/javascript">
    var monthAbbr = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

    // returns last day of the month.
    function getLastDayOfMonth(mth,yr){
        if(mth == 1){
            if((yr % 4) == 0){
                return 29;
            }else{
                return 28;
            }
        }else if((mth == 0)||(mth == 2)||(mth == 4)||(mth == 6)||(mth == 7)||(mth == 9)||(mth == 11)){
            return 31;
        }
        return 30;
    }
    
        // populates period selects
    function populatePeriod(){
        var i, selectedYr;
        var now = new Date();
        
        for(i = 2005;i <= now.getFullYear();i++){
            document.getElementById("VulChart.period_from_yr").options[i-2005] = new Option(i,i);
            document.getElementById("VulChart.period_to_yr").options[i-2005] = new Option(i,i);
        }
        document.getElementById("VulChart.period_from_yr").selectedIndex = 0;
        document.getElementById("VulChart.period_to_yr").selectedIndex = 0;

        updatePeriodFromMth(now);
        updatePeriodToMth(now);
    }

    // updates options of specified month select
    function updatePeriodMth(now,id,selectedYr){
        var i, selectedMth = document.getElementById(id).selectedIndex;
        var select;
        
        select = document.getElementById(id);
        while(select.length > 0) { select.options[0] = null; }
        
        if(selectedYr == now.getFullYear()){
            
            for(i = 0;i <= now.getMonth();i++){
                select.options[i] = new Option(monthAbbr[i], i);
            }
        }else if(selectedYr < now.getFullYear()){
            for(i = 0;i < 12;i++){
                select.options[i] = new Option(monthAbbr[i], i);
            }        
        }else{ alert("invalid year selected!"); }

        if(selectedMth >= 0){
            if(selectedMth < select.length){
                select.selectedIndex = selectedMth;
            }else{
                select.selectedIndex = select.length - 1;
            }
        }
    }

    function updatePeriodFromMth(now){
        selectedYr = document.getElementById("VulChart.period_from_yr").options[document.getElementById("VulChart.period_from_yr").selectedIndex].value;
        updatePeriodMth(now,"VulChart.period_from_mth", selectedYr);
    }
    
    function updatePeriodToMth(now){
        selectedYr = document.getElementById("VulChart.period_to_yr").options[document.getElementById("VulChart.period_to_yr").selectedIndex].value;
        updatePeriodMth(now,"VulChart.period_to_mth", selectedYr);
    }
    
    function VulChart(){
        this.minWidth = 320;
        this.minHeight = 180;
        this.maxWidthMonths = 720;
        this.maxHeightMonths = 405;
        this.maxWidthCountries = 390;
        this.maxHeightCountries = 220;

        this.tSearcher = null;
        
        this.now = null;
        this.fromMth = -1;
        this.fromYr = -1;
        this.toMth = -1;
        this.toYr = -1;
        this.dataType = "none";
        this.dataTypeParam = null;
        this.against = "months";
        
        this.maxValue = 0;
        this.value = null; // array of raw data
        this.key1 = null; // array of data labels (month/country)
        this.key2 = null; // array of data labels (year)
        
        this.queryCount = 0;
        this.queryEnd = 0;
    }
    
    // initialization
    VulChart.prototype.init = function(){
        this.tSearcher = new TruveoVideoSearch('6383cabacdba1f3a3');
        this.tSearcher.attachEvent('onerror', 'onTVSError(errorCode,errorMessage);');
        this.tSearcher.attachEvent('onload', 'onTVSLoad();');
        this.tSearcher.attachEvent('onupdate', 'onTVSUpdate();');
        
        this.tSearcher.results = 1;
        this.tSearcher.showAdult = 0;
        
        this.tSearcher.initialize();
    }
    
    // build day filter based on given range
    VulChart.prototype.buildDayFilter = function(now,mth,yr){
        var diff = Date.UTC(now.getFullYear(),now.getMonth(),now.getDate(),0,0,0) - Date.UTC(yr,mth,1,0,0,0);
        var fromDay = diff/1000/60/60/24;
        var toDay;
        
        if(fromDay <= 0){ return "days_old:<0"; }
        
        if((yr == now.getFullYear()) && (mth == now.getMonth())){
            toDay = 0;
        }else{
            toDay = fromDay - getLastDayOfMonth(mth,yr);
        }
        
        return "days_old:>"+toDay+" days_old:<"+fromDay;
    }
    
    // build day filter based on period
    VulChart.prototype.buildDayFilterPeriod = function(now){
        var nowUTC = Date.UTC(now.getFullYear(),now.getMonth(),now.getDate(),0,0,0);
        var fromUTC = Date.UTC(this.fromYr,this.fromMth,1,0,0,0);
        var day, toUTC, fromDay, toDay;
        
        fromDay = (nowUTC - fromUTC)/1000/60/60/24;
        if(fromDay <= 0){ return "days_old:<0"; }

        day = getLastDayOfMonth(this.toMth,this.toYr);
        
        toUTC = Date.UTC(this.toYr,this.toMth,day,0,0,0);
        toDay = Math.max(0,(nowUTC - toUTC)/1000/60/60/24);
        
        return "days_old:>"+toDay+" days_old:<"+fromDay;
    }

    //    preparation for query data against months
    VulChart.prototype.prepareForOppMonth = function(){
        // compute number of months, i.e. size of data
        if(this.fromYr > this.toYr){
            this.queryEnd = 0;
        }else if(this.fromYr == this.toYr){
            if(this.fromMth >= this.toMth){
                this.queryEnd = 0;
            }else{
                this.queryEnd = this.toMth - this.fromMth;
            }
        }else{
            this.queryEnd = (this.toYr - this.fromYr - 1) * 12;
            this.queryEnd += this.toMth;
            this.queryEnd += 12 - this.fromMth;
        }
        
        // allocates array for data storage
        this.value = new Array(this.queryEnd + 1);
        this.key1 = new Array(this.queryEnd + 1);
        this.key2 = new Array(this.queryEnd + 1);
        
        // fills keys with months and years (to be used to generate chart's labels)
        for(i = 0;i <= this.queryEnd;i++){
            this.key1[i] = 11 - ((11 - this.toMth + i) % 12);
            
            this.key2[i] = this.toYr;
            cnt = i - this.toMth;
            if(cnt > 0){ this.key2[i] -= Math.ceil(cnt / 12); }
        }
    }
    
    // preparation for query data against countries
    VulChart.prototype.prepareForOppCountry = function(){
        // only countries with more than 10 million population included
        this.key1 = ["AF","AX","DZ","AO","AQ","AR","AU",
            "BD","BE","BV","BR","IO","BF",
            "KH","CM","CA","TD","CL","CN","CX","CC","CO","CG","CI","CU","CZ",
            "EC","EG","ET",
            "FR","TF",
            "DE","GH","DR","GT",
            "HM","VA","HU",
            "IN","ID","IR","IQ","IT",
            "JP",
            "KZ","KE","KP","KR",
            "LT",
            "MG","MW","MY","ML","MX","MA","MZ","MM",
            "NP","NL","NE","NG","NF",
            "PK","PE","PH","PL","PT",
            "RO","RU",
            "SA","SN","ZA","GS","ES","LK","SD","SJ","SY",
            "TW","TZ","TH","TN","TR",
            "UG","UA","GB","US","UM","UZ",
            "VE","VN",
            "YE",
            "ZM","ZW"];
        this.value = new Array(this.key1.length);

        this.queryEnd = this.key1.length - 1;
    }
    
    // queries data and generates chart
    VulChart.prototype.generateChart = function(){
        var i, cnt, radios, select;

        document.getElementById("VulChart.generate").disabled = true;
        
        // prepare data range
        this.now = new Date();
        this.fromMth = parseInt(document.getElementById("VulChart.period_from_mth").options[document.getElementById("VulChart.period_from_mth").selectedIndex].value);
        this.fromYr = parseInt(document.getElementById("VulChart.period_from_yr").options[document.getElementById("VulChart.period_from_yr").selectedIndex].value);
        this.toMth = parseInt(document.getElementById("VulChart.period_to_mth").options[document.getElementById("VulChart.period_to_mth").selectedIndex].value);
        this.toYr = parseInt(document.getElementById("VulChart.period_to_yr").options[document.getElementById("VulChart.period_to_yr").selectedIndex].value);
        
        radios = document.getElementsByName("VulChart.dataType");
        for(i = (radios.length - 1);i >= 0;--i){
            if(radios[i].checked){
                this.dataType = radios[i].value;
                if(this.dataType == "category"){
                    select = document.getElementById("VulChart.category");
                    this.dataTypeParam = select.options[select.selectedIndex].value;
                }else if(this.dataType == "country"){
                    select = document.getElementById("VulChart.country");
                    this.dataTypeParam = select.options[select.selectedIndex].value;
                }
                break;
            }
        }
        
        radios = document.getElementsByName("VulChart.against");
        for(i = (radios.length - 1);i >= 0;--i){
            if(radios[i].checked){
                this.against = radios[i].value;
                if(this.against == "months"){
                    // hide label
                    document.getElementById("VulChart.label").style.display = "none";
                    
                    this.prepareForOppMonth();
                }else if(this.against == "countries"){
                    // show label
                    document.getElementById("VulChart.label").style.display = "inline";

                    this.prepareForOppCountry();
                }
                break;
            }
        }
                
        document.getElementById("VulChart.debug").innerHTML = "queryEnd=" + this.queryEnd + "<br>";

        this.maxValue = 0;
        this.queryCount = 0;
        if(this.queryCount <= this.queryEnd){
            this.queryTVS();
        }else{
            this.drawChart();
        }
    }
    
    // sends query to truveo searcher
    VulChart.prototype.queryTVS = function(){
        var query;
        
        if(this.against == "months"){
            query = this.buildDayFilter(this.now,this.key1[this.queryCount],this.key2[this.queryCount]);
            if(this.dataType == "category"){
                query += " category:"+this.dataTypeParam;
            }else if(this.dataType == "country"){
                query += " country:"+this.dataTypeParam;
            }
        }else if(this.against == "countries"){
            query = this.buildDayFilterPeriod(this.now);
            if(this.dataType == "category"){
                query += " categorty:"+this.dataTypeParam;
            }
            query += " country:"+this.key1[this.queryCount];
        }
 
        document.getElementById("VulChart.debug").innerHTML += "queryCount=" + this.queryCount + "<br>";
        document.getElementById("VulChart.debug").innerHTML += "key1=" + this.key1[this.queryCount] + "<br>";
        if(this.against == "months"){
            document.getElementById("VulChart.debug").innerHTML += "key2=" + this.key2[this.queryCount] + "<br>";
        }
        document.getElementById("VulChart.debug").innerHTML += query + "<br>";
        
        this.tSearcher.getVideos(query);
    }
    
    // computes chart size for against months
    VulChart.prototype.computeChartSizeMth = function(){
        var w = Math.max(this.minWidth, Math.min(this.maxWidthMonths,document.body.clientWidth));
        var h = w * 9 / 16;
        h = Math.max(this.minHeight, Math.min(this.maxHeightMonths,h));
        
        return Math.floor(w)+"x"+Math.floor(h);
    }
    
    // draws against month chart
    VulChart.prototype.drawChartMth = function(){
        var i, v, step, maxLength, maxRoundUp;
        var url = "http://chart.apis.google.com/chart?cht=bvs&chs="+this.computeChartSizeMth();
        
        i = this.maxValue;
        if(0 == i){
            maxLength = 1;
        }else{
            for(maxLength = 0;1 <= i;maxLength++){ i /= 10; }
        }
        step = Math.pow(10, maxLength - 1);
        maxRoundUp = Math.ceil(this.maxValue / step) * step;
               
        url += "&chd=t:";
        for(i = 0;i < this.queryCount;i++){
            if(0 == maxRoundUp){
                url += "0";
            }else{
                v = this.value[i] / maxRoundUp * 100;
                url += v.toFixed(2);
            }
            
            if(i < (this.queryCount - 1)) { url += ","; }
        }
        
        url += "&chxt=x,x,y&chxl=0:|";
        
        // x-axis label
        for(i = 0;i < this.queryCount;i++){
            url += monthAbbr[this.key1[i]];
            url += "|";
        }
        
        // x-axis label 2
        url += "1:|";
        for(i = 0;i < this.queryCount;i++){
            if((0 == i) || (11 == this.key1[i])){
                url += this.key2[i];
            }
            url += "|";
        }
                
        // y-axis label
        step = Math.pow(10, maxLength - 1);
        url += "2:|0";
        i = step;
        while(i <= this.maxValue){
            url += "|"+i;
            i += step;
        };
        if((i - step) < this.maxValue) { url += "|"+i; }
        
        document.getElementById("VulChart.chart").src = url;
    }

    // computes chart size for against countries charts
    VulChart.prototype.computeChartSizeCountry = function(){
        var w = Math.max(this.minWidth, Math.min(this.maxWidthCountries,document.body.clientWidth));
        var h = w * 9 / 16;
        h = Math.max(this.minHeight, Math.min(this.maxHeightCountries,h));
        
        return Math.floor(w)+"x"+Math.floor(h);
    }
    
    // draws against country chart
    VulChart.prototype.drawChartCountry = function(){
        var i, v;
        var url = "http://chart.apis.google.com/chart?cht=t&chtm=world&chco=ffffff,ffff00,ff0000&chf=bg,s,EAF7FE&chs="+this.computeChartSizeCountry();
       
        url += "&chd=t:";
        for(i = 0;i < this.queryCount;i++){
            if(0 == this.maxValue){
                url += "0";
            }else{
                v = this.value[i] / this.maxValue * 100;
                url += v.toFixed(2);
            }
            
            if(i < (this.queryCount - 1)) { url += ","; }
        }
        
        url += "&chld=";
        for(i = 0;i < this.queryCount;i++){
            url += this.key1[i];
        }
        
        document.getElementById("VulChart.chart").src = url;        
    }
    
    // draws chart
    VulChart.prototype.drawChart = function(){
        if(this.against == "months"){
            this.drawChartMth();
        }else if(this.against == "countries"){
            this.drawChartCountry();
        }
        document.getElementById("VulChart.generate").disabled = false;
    }
    
    // handles responses from data query
    VulChart.prototype.onTVSUpdate = function(){
        this.maxValue = Math.max(this.maxValue,this.tSearcher.VideoSet.totalResultsAvailable);
        this.value[this.queryCount] = parseInt(this.tSearcher.VideoSet.totalResultsAvailable);
        
        document.getElementById("VulChart.debug").innerHTML += this.tSearcher.VideoSet.totalResultsAvailable + "<br><br>";
        
        this.queryCount++;
        if(this.queryCount <= this.queryEnd){
            this.queryTVS();
        }else{
            this.drawChart();
        }
    }
    
    var vulchart = new VulChart();
    
    // handles truveo video searcher loaded event
    function onTVSLoad(){ document.getElementById("VulChart.generate").disabled = false; }
    
    // handles truveo video searcher query responses
    function onTVSUpdate(){ vulchart.onTVSUpdate(); }
    
    // handles truveo video searcher error
    function onTVSError(errorCode,errorMessage){ alert("TVS error:"+errorCode+" "+errorMessage); }
    
    function init(){
        populatePeriod();
        vulchart.init();
    }
    
    function onGadgetResize(){
        var url = document.getElementById("VulChart.chart").src;
        if(url.search(/cht=bvs/) != -1){
            url = url.replace(/chs=[0-9]+x[0-9]+/, "chs="+vulchart.computeChartSizeMth());
        }else if(url.search(/cht=t/) != -1){
            url = url.replace(/chs=[0-9]+x[0-9]+/, "chs="+vulchart.computeChartSizeCountry());
        }
        document.getElementById("VulChart.chart").src = url;
    }
        
    self.onresize = onGadgetResize;    
    </script>   
</head>

<body onload="init()">
    <div id="VulChart.data">
        Starting from
        <select id="VulChart.period_from_mth"></select><select id="VulChart.period_from_yr" onchange="updatePeriodFromMth(new Date())"></select> to
        <select id="VulChart.period_to_mth"></select><select id="VulChart.period_to_yr" onchange="updatePeriodToMth(new Date())"></select>
        <br>
        <table style="margin-top:1;margin-bottom:1" cellpadding="0" cellspacing="0">
            <tr>
                <td>Videos from</td>
                <td><input type="radio" name="VulChart.dataType" value="category" checked>category</input>
                <select id="VulChart.category">
                    <option selected>News</option>
                    <option>Sports</option>
                    <option>Entertainment</option>
                    <option>Science</option>
                    <option>Music</option>
                    <option>Movies</option>
                    <option>Comedy</option>
                </select></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="radio" name="VulChart.dataType" value="country">country</input>
                <select id="VulChart.country">
                    <option value="au">Australia</option>
                    <option value="sg" selected>Singapore</option>
                    <option value="us">United States</option>
                </select></td>
            </tr>
        </table>
        Against <input type="radio" name="VulChart.against" value="months" checked>months</input>
        <input type="radio" name="VulChart.against" value="countries">countries</input>
        <button id="VulChart.generate" onclick="vulchart.generateChart()" disabled>Generate Chart</button>
    </div>
    <br><img id="VulChart.chart" alt="Click the 'Generate Chart' button to generate chart."></img>
    <br><div id="VulChart.label" style="display:none">
        <table cellpadding="0" cellspacing="0">
            <tr><td><table height="18" width="18" style="border:1px solid #000000;background-color:#ffffff"><tr><td></td></tr></table></td><td>&nbsp;Excluded countries</td></tr>
            <tr><td><table height="18" width="18" style="border:1px solid #000000;background-color:#ffff00"><tr><td></td></tr></table></td><td>&nbsp;Low uploads</td></tr>
            <tr><td><table height="18" width="18" style="border:1px solid #000000;background-color:#ff0000"><tr><td></td></tr></table></td><td>&nbsp;High uploads</td></tr>
        </table>
    </div>
    <br><div id="VulChart.debug"></div>
</body>